package com.yx.backstage.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yx.backstage.config.global.BizException;
import com.yx.backstage.enums.IntBoolean;
import com.yx.backstage.model.SysUser;
import com.yx.backstage.security.LoginUser;
import com.yx.backstage.service.SysPermissionService;
import com.yx.backstage.service.SysUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author YangXiong
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount, account);
        queryWrapper.eq(SysUser::getIsManager, IntBoolean.YES.getKey());
        SysUser user = sysUserService.getOne(queryWrapper);
        if (Objects.isNull(user)) {
            throw new BizException("用户" + account + "不存在");
        }
        List<String> permissionKeyList =  sysPermissionService.selectPermsByUserId(user.getId());
        return new LoginUser(user, permissionKeyList);
    }
}
